package com.example.Servlet;
import com.example.Pojo.HairMaster;
import com.example.Pojo.Member;
import com.example.Pojo.Profit;
import com.example.Pojo.User;
import com.example.dao.impl.AdminManagerImpl;
import com.example.dao.impl.UserDaoImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpCookie;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Login extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String action = req.getParameter("action");
        if ("register".equals(action)){
            System.out.println("注册~");
            register(req,resp);
        }else if ("logIn".equals(action)){
            System.out.println("登录~");
            logIn(req,resp);
        }else if ("show".equals(action)){
            System.out.println("showAllUser");
            showAllUser(req,resp);
        }
        else {
            System.out.println("无可操作函数");
        }
    }

    public void register(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String tellphone = req.getParameter("tellphone");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String level = req.getParameter("level");
        User user = new User();
        HairMaster hm = new HairMaster();
        if (new UserDaoImpl().queryUser(username) != null){
           //说明该用户名已经注册
            System.out.println("用户名已经存在!");
            resp.sendRedirect("/Barbr/html/regist.html");
        }else{
            //说明用户名没有被注册，可以直接保存
            //理发师插入hairmaster表
            hm.setUsername(username);
            hm.setTelephone(tellphone);
            hm.setSex(sex);
            hm.setLevel(level);
            //插入admin表 理发师id默认barber
            user.setId("barber");
            user.setUsername(username);
            user.setPassword(password);
            user.setTellphone(tellphone);
            user.setRegisttime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            if (new UserDaoImpl().saveUser(user) >0 && new AdminManagerImpl().insertInfo(hm) >0){
                System.out.println("注册成功!");
                resp.sendRedirect("/Barbr/html/login.jsp");
            }else{
                System.out.println("注册失败!");
                resp.sendRedirect("/Barbr/html/regist.html");
            }
        }
    }

    public void logIn(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{

        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String check = req.getParameter("rememberMe");
        //登录时首先查看用户名是否存在
        User user = null;   //user接口和admin表已对接
        user = new UserDaoImpl().queryUser(username);       //获取登录时用户名所对应的用户对象，得到则验证密码反之错误
        if ( user != null){
            //查找用户名结果不为空，则存在，继续验证密码
            if (user.getPassword().equals(password) == true){
                HttpSession session = req.getSession();
                session.setAttribute("username",username);
                session.setAttribute("regist",user.getRegisttime());
                session.setAttribute("tellphone",user.getTellphone());
                System.out.println("登录成功!");
                try{
                    if (check != null && check.equals("on")){
                        Cookie cookie = new Cookie("username",username);
                        cookie.setMaxAge(60*60);    //cookie保存一小时
                        cookie.setPath("/");    //该目录下所有都可用该cookie
                        resp.addCookie(cookie);
                }else{
                    //未勾选记住我，则销毁已存在的所有cookie
                    Cookie[] cookies = req.getCookies();
                    for (Cookie c:cookies){
                        c.setMaxAge(0);
                    }
                    System.out.println("未勾选记住我!");
                }
                }catch (Exception e){
                    e.printStackTrace();
                }
                if (user.getId().equals("customer")){
                    //客户登录
                    session.setAttribute("customer",user);
                    resp.sendRedirect("/Barbr/html/reserve.jsp");  //选用请求重定向为了解决请求转发引起的表单多次提交问题
                }else if(user.getId().equals("barber")){
                    //理发师
                    List<HairMaster> list = new AdminManagerImpl().findAll();
                    session.setAttribute("barber",list);
                    session.setMaxInactiveInterval(60*60*24);
                    resp.sendRedirect("/Barbr/html/MembershipManagement.jsp");  //选用请求重定向为了解决请求转发引起的表单多次提交问题
                }else {
                    //管理员
                    List<HairMaster> list = new UserDaoImpl().findAllMaster();
                    List<Profit> profits = new AdminManagerImpl().selectProfit();
                    session.setAttribute("profit",profits);
                    session.setAttribute("hairmaster",list);
                    session.setMaxInactiveInterval(60*60*24);
                    resp.sendRedirect("/Barbr/html/master.jsp");
                }
            }else {
                System.out.println("密码错误!");
                resp.sendRedirect(req.getHeader("Referer"));
            }
        }else {
            System.out.println("用户名不存在!");
            resp.sendRedirect(req.getHeader("Referer"));
        }
    }
    public void showAllUser(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();
        Gson gson = new Gson();
        List<Member> memberList =  new UserDaoImpl().showAllUser();


        String json = gson.toJson(memberList);
        //System.out.println(json);
        out.print(json);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
